{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本次实验任务：以西瓜数据集3.0为例，使用朴素贝叶斯分类算法建立一个模型，并根据朴素贝叶斯分类算法流程对模型进行训练，得到一个能够准确对西瓜好坏进行识别的模型。\n",
    "提交要求：（1）文本框插入“朴素贝叶斯分类算法实现代码”；（2）模型运行结果；（3）学习过程的心得体会、问题、建议（可参考亮考帮形式撰写）；（4）上传源代码。\n",
    "如下代码框架可供参考："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import math"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class NaiveBayesClassifier(object):\n",
    "    def __init__(self):\n",
    "        '''\n",
    "        self.label_prob表示每种类别在数据中出现的概率\n",
    "        例如，{0:0.333, 1:0.667}表示数据中类别0出现的概率为0.333，类别1的概率为0.667\n",
    "        '''\n",
    "        self.label_prob = {}\n",
    "        '''\n",
    "        self.condition_prob表示每种类别确定的条件下各个特征出现的概\n",
    "        例如训练数据集中的特征为 [[2, 1, 1],\n",
    "                              [1, 2, 2],\n",
    "                              [2, 2, 2],\n",
    "                              [2, 1, 2],\n",
    "                              [1, 2, 3]]\n",
    "        标签为[1, 0, 1, 0, 1]\n",
    "        那么当标签为0时第0列的值为1的概率为0.5，值为2的概率为0.5;\n",
    "        当标签为0时第1列的值为1的概率为0.5，值为2的概率为0.5;\n",
    "        当标签为0时第2列的值为1的概率为0，值为2的概率为1，值为3的概率为0;\n",
    "        当标签为1时第0列的值为1的概率为0.333，值为2的概率为0.666;\n",
    "        当标签为1时第1列的值为1的概率为0.333，值为2的概率为0.666;\n",
    "        当标签为1时第2列的值为1的概率为0.333，值为2的概率为0.333,值为3的概率为0.333;\n",
    "        因此self.label_prob的值如下：     \n",
    "        {\n",
    "            0:{\n",
    "                0:{\n",
    "                    1:0.5\n",
    "\n",
    "                    2:0.5\n",
    "                }\n",
    "                1:{\n",
    "                    1:0.5\n",
    "                    2:0.5\n",
    "                }\n",
    "                2:{\n",
    "                    1:0\n",
    "                    2:1\n",
    "                    3:0\n",
    "                }\n",
    "            }\n",
    "            1:\n",
    "            {\n",
    "                0:{\n",
    "                    1:0.333\n",
    "                    2:0.666\n",
    "                }\n",
    "                1:{\n",
    "                    1:0.333\n",
    "                    2:0.666\n",
    "                }\n",
    "                2:{\n",
    "                    1:0.333\n",
    "                    2:0.333\n",
    "                    3:0.333\n",
    "                }\n",
    "            }\n",
    "        }\n",
    "        '''\n",
    "        self.condition_prob = {}\n",
    "\n",
    "    def fit(self, feature, label):\n",
    "        '''\n",
    "        对模型进行训练，需要将各种概率分别保存在self.label_prob和self.condition_prob中\n",
    "        :param feature: 训练数据集所有特征组成的ndarray\n",
    "        :param label:训练数据集中所有标签组成的ndarray\n",
    "        :return: 无返回\n",
    "        '''\n",
    "\n",
    "        #********* Begin *********#\n",
    "        label_set = set(label)\n",
    "        N = len(label_set)\n",
    "        for i in label_set:\n",
    "            count = 0\n",
    "            for j in range(len(label)):\n",
    "                if label[j] == i:\n",
    "                    count += 1\n",
    "            self.label_prob[i] = round((count + 1)/(len(label) + N),3)\n",
    "        \n",
    "        for j in label_set:\n",
    "            self.condition_prob[j] = {}\n",
    "            N = 0\n",
    "            for p in range(len(feature)):\n",
    "                if label[p] == j:\n",
    "                    N += 1\n",
    "            for i in range(feature.shape[1] - 2):\n",
    "                self.condition_prob[j][i] = {}\n",
    "                for q in range(3):\n",
    "                    count = 0\n",
    "                    for p in range(len(feature)):\n",
    "                        if label[p] == j and feature[p][i] == q:\n",
    "                            count += 1\n",
    "                    #self.condition_prob[i][j][q] = round(count/N,3)\n",
    "                    self.condition_prob[j][i][q] = round((count + 1)/(N+3),3) #加入拉普拉斯修正\n",
    "        \n",
    "        for j in label_set:\n",
    "            N = 0\n",
    "            for p in range(len(feature)):\n",
    "                if label[p] == j:\n",
    "                    N += 1\n",
    "            for i in range(feature.shape[1] - 2,feature.shape[1]):\n",
    "                self.condition_prob[j][i] = {}\n",
    "                variance = 0\n",
    "                sum = 0\n",
    "                vum = 0\n",
    "                for p in range(len(feature)):\n",
    "                    if label[p] == j:\n",
    "                        sum += feature[p][i]\n",
    "                mean = sum/N\n",
    "                for p in range(len(feature)):\n",
    "                    if label[p] == j:\n",
    "                        vum += np.square(feature[p][i] - mean)\n",
    "                variance = vum/N\n",
    "                self.condition_prob[j][i]['mean'] = round(mean,3)\n",
    "                self.condition_prob[j][i]['variance'] = round(variance,3)\n",
    "        #********* End *********#\n",
    "\n",
    "    def predict(self, feature):\n",
    "        '''\n",
    "        对数据进行预测，返回预测结果\n",
    "        :param feature:测试数据集所有特征组成的ndarray\n",
    "        :return:\n",
    "        '''\n",
    "\n",
    "        # ********* Begin *********#\n",
    "        result = []\n",
    "        for i in range(len(feature)):\n",
    "            pre = [1,1]\n",
    "            for j in range(2):\n",
    "                for p in range(feature.shape[1] - 2):\n",
    "                    pre[j] = pre[j]*self.condition_prob[j][p][feature[i][p]]\n",
    "                for p in range(feature.shape[1] - 2,feature.shape[1]):\n",
    "                    mean = self.condition_prob[j][p]['mean']         #取出相应均值\n",
    "                    variance =self.condition_prob[j][p]['variance']  #取出相应\n",
    "                    pre[j] = pre[j]*round(1/np.sqrt(2*3.14*variance)*math.exp(-np.square(feature[i][p] - mean)/2*variance),3)\n",
    "            pre[j] = pre[j]*self.label_prob[j]\n",
    "        \n",
    "            if pre[0] > pre[1]:\n",
    "                result.append(0)\n",
    "            else:\n",
    "                result.append(1)\n",
    "        return result\n",
    "        #********* End *********#\n",
    "\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn import tree\n",
    "# from sklearn.metrics import precision_recall_curve\n",
    "from sklearn.metrics import classification_report\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn import preprocessing\n",
    "from io import StringIO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据准备\n",
    "def createDataSet():\n",
    "    ''' 数据读入 '''\n",
    "    rawData = StringIO(\n",
    "    \"\"\"编号,色泽,根蒂,敲声,纹理,脐部,触感,密度,含糖率,好瓜\n",
    "    1,青绿,蜷缩,浊响,清晰,凹陷,硬滑,0.697,0.460,是\n",
    "    2,乌黑,蜷缩,沉闷,清晰,凹陷,硬滑,0.774,0.376,是\n",
    "    3,乌黑,蜷缩,浊响,清晰,凹陷,硬滑,0.634,0.264,是\n",
    "    4,青绿,蜷缩,沉闷,清晰,凹陷,硬滑,0.608,0.318,是\n",
    "    5,浅白,蜷缩,浊响,清晰,凹陷,硬滑,0.556,0.215,是\n",
    "    6,青绿,稍蜷,浊响,清晰,稍凹,软粘,0.403,0.237,是\n",
    "    7,乌黑,稍蜷,浊响,稍糊,稍凹,软粘,0.481,0.149,是\n",
    "    8,乌黑,稍蜷,浊响,清晰,稍凹,硬滑,0.437,0.211,是\n",
    "    9,乌黑,稍蜷,沉闷,稍糊,稍凹,硬滑,0.666,0.091,否\n",
    "    10,青绿,硬挺,清脆,清晰,平坦,软粘,0.243,0.267,否\n",
    "    11,浅白,硬挺,清脆,模糊,平坦,硬滑,0.245,0.057,否\n",
    "    12,浅白,蜷缩,浊响,模糊,平坦,软粘,0.343,0.099,否\n",
    "    13,青绿,稍蜷,浊响,稍糊,凹陷,硬滑,0.639,0.161,否\n",
    "    14,浅白,稍蜷,沉闷,稍糊,凹陷,硬滑,0.657,0.198,否\n",
    "    15,乌黑,稍蜷,浊响,清晰,稍凹,软粘,0.360,0.370,否\n",
    "    16,浅白,蜷缩,浊响,模糊,平坦,硬滑,0.593,0.042,否\n",
    "    17,青绿,蜷缩,沉闷,稍糊,稍凹,硬滑,0.719,0.103,否\n",
    "\"\"\")\n",
    "    df = pd.read_csv(rawData, sep=\",\") \n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>编号</th>\n",
       "      <th>色泽</th>\n",
       "      <th>根蒂</th>\n",
       "      <th>敲声</th>\n",
       "      <th>纹理</th>\n",
       "      <th>脐部</th>\n",
       "      <th>触感</th>\n",
       "      <th>密度</th>\n",
       "      <th>含糖率</th>\n",
       "      <th>好瓜</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>青绿</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>0.697</td>\n",
       "      <td>0.460</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>乌黑</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>0.774</td>\n",
       "      <td>0.376</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>乌黑</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>0.634</td>\n",
       "      <td>0.264</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>青绿</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>沉闷</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>0.608</td>\n",
       "      <td>0.318</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>浅白</td>\n",
       "      <td>蜷缩</td>\n",
       "      <td>浊响</td>\n",
       "      <td>清晰</td>\n",
       "      <td>凹陷</td>\n",
       "      <td>硬滑</td>\n",
       "      <td>0.556</td>\n",
       "      <td>0.215</td>\n",
       "      <td>是</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   编号  色泽  根蒂  敲声  纹理  脐部  触感     密度    含糖率 好瓜\n",
       "0   1  青绿  蜷缩  浊响  清晰  凹陷  硬滑  0.697  0.460  是\n",
       "1   2  乌黑  蜷缩  沉闷  清晰  凹陷  硬滑  0.774  0.376  是\n",
       "2   3  乌黑  蜷缩  浊响  清晰  凹陷  硬滑  0.634  0.264  是\n",
       "3   4  青绿  蜷缩  沉闷  清晰  凹陷  硬滑  0.608  0.318  是\n",
       "4   5  浅白  蜷缩  浊响  清晰  凹陷  硬滑  0.556  0.215  是"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = createDataSet()\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基于LabelEncoder的类别变量重编码\n",
    "class MultiColumnLabelEncoder:\n",
    "    def __init__(self,columns = None):\n",
    "        self.columns = columns # array of column names to encode\n",
    "    def fit(self,X,y=None):\n",
    "        return self # not relevant here\n",
    "    def transform(self,X):\n",
    "        '''\n",
    "        Transforms columns of X specified in self.columns using\n",
    "        LabelEncoder(). If no columns specified, transforms all\n",
    "        columns in X.\n",
    "        '''\n",
    "        output = X.copy()\n",
    "        if self.columns is not None:\n",
    "            for col in self.columns:\n",
    "                if col == '密度' or col=='含糖率':\n",
    "                    continue\n",
    "                output[col] = LabelEncoder().fit_transform(output[col])\n",
    "        else:\n",
    "            for colname,col in output.iteritems():\n",
    "                output[colname] = LabelEncoder().fit_transform(col)\n",
    "        return output\n",
    "    def fit_transform(self,X,y=None):\n",
    "        return self.fit(X,y).transform(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    编号  色泽  根蒂  敲声  纹理  脐部  触感     密度    含糖率  好瓜\n",
      "0    1   2   2   1   1   0   0  0.697  0.460   1\n",
      "1    2   0   2   0   1   0   0  0.774  0.376   1\n",
      "2    3   0   2   1   1   0   0  0.634  0.264   1\n",
      "3    4   2   2   0   1   0   0  0.608  0.318   1\n",
      "4    5   1   2   1   1   0   0  0.556  0.215   1\n",
      "5    6   2   1   1   1   2   1  0.403  0.237   1\n",
      "6    7   0   1   1   2   2   1  0.481  0.149   1\n",
      "7    8   0   1   1   1   2   0  0.437  0.211   1\n",
      "8    9   0   1   0   2   2   0  0.666  0.091   0\n",
      "9   10   2   0   2   1   1   1  0.243  0.267   0\n",
      "10  11   1   0   2   0   1   0  0.245  0.057   0\n",
      "11  12   1   2   1   0   1   1  0.343  0.099   0\n",
      "12  13   2   1   1   2   0   0  0.639  0.161   0\n",
      "13  14   1   1   0   2   0   0  0.657  0.198   0\n",
      "14  15   0   1   1   1   2   1  0.360  0.370   0\n",
      "15  16   1   2   1   0   1   0  0.593  0.042   0\n",
      "16  17   2   2   0   2   2   0  0.719  0.103   0\n"
     ]
    }
   ],
   "source": [
    "df = MultiColumnLabelEncoder(columns=['色泽', '根蒂', '敲声', '纹理', '脐部', '触感', '好瓜','密度','含糖率']).fit_transform(df)\n",
    "# df.head()\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据划分\n",
    "from sklearn import model_selection \n",
    "feature_names = ['色泽','根蒂','敲声','纹理','脐部','触感','密度','含糖率']\n",
    "target_names = ['是', '否']\n",
    "feature = df[feature_names]\n",
    "label = df['好瓜']\n",
    "x = feature\n",
    "y = label\n",
    "x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y,test_size=0.3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "condition_prob: {0: {0: {0: 0.333, 1: 0.333, 2: 0.333}, 1: {0: 0.222, 1: 0.444, 2: 0.333}, 2: {0: 0.444, 1: 0.333, 2: 0.222}, 3: {0: 0.222, 1: 0.333, 2: 0.444}, 4: {0: 0.222, 1: 0.333, 2: 0.444}, 5: {0: 0.556, 1: 0.333, 2: 0.111}, 6: {'mean': 0.54, 'variance': 0.031}, 7: {'mean': 0.179, 'variance': 0.013}}, 1: {0: {0: 0.5, 1: 0.25, 2: 0.25}, 1: {0: 0.125, 1: 0.5, 2: 0.375}, 2: {0: 0.25, 1: 0.625, 2: 0.125}, 3: {0: 0.125, 1: 0.625, 2: 0.25}, 4: {0: 0.375, 1: 0.125, 2: 0.5}, 5: {0: 0.5, 1: 0.375, 2: 0.125}, 6: {'mean': 0.53, 'variance': 0.017}, 7: {'mean': 0.238, 'variance': 0.006}}}\n",
      "label_prob: {0: 0.538, 1: 0.462}\n"
     ]
    }
   ],
   "source": [
    "#配置模型\n",
    "naiveBayesClassifier = NaiveBayesClassifier()\n",
    "naiveBayesClassifier.fit(np.array(x_train),np.array(y_train))\n",
    "print('condition_prob:',naiveBayesClassifier.condition_prob)\n",
    "print('label_prob:',naiveBayesClassifier.label_prob)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "#模型预测\n",
    "y_te_pred = naiveBayesClassifier.predict(np.array(x_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "naiveBayesClassifier 模型评估\n",
      "accuracy:0.83\n",
      "[1, 0, 1, 0, 1, 1]\n",
      "[1 0 1 0 1 0]\n"
     ]
    }
   ],
   "source": [
    "#模型评估\n",
    "from sklearn.metrics import accuracy_score\n",
    "# 基于精确率的模型评估\n",
    "print(\"naiveBayesClassifier 模型评估\")\n",
    "accuracy = accuracy_score(y_te_pred, np.array(y_test))\n",
    "print('accuracy:{}'.format(round(accuracy,2)))\n",
    "print(y_te_pred)\n",
    "print(np.array(y_test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请点击[此处](https://ai.baidu.com/docs#/AIStudio_Project_Notebook/a38e5576)查看本环境基本用法.  <br>\n",
    "Please click [here ](https://ai.baidu.com/docs#/AIStudio_Project_Notebook/a38e5576) for more detailed instructions. "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
